//
//  WMPaymentCenterController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/5.
//

import UIKit
import SwiftyStoreKit

class WMPaymentCenterController: WMBaseViewController {
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var topViewTopConstant: NSLayoutConstraint!
    
    var productList: [WMPackageListModel] = []
    var payIndex: Int = -1
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航栏标题
        customNavBar.setTitle("支付中心")
        topViewTopConstant.constant = 44
        // 保持透明导航栏样式
        customNavBar.setStyle(.transparent)
        // 添加右侧按钮
        customNavBar.addRightButton(title: "恢复购买", tintColor:UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0), target: self, action: #selector(rightButtonClicked))
        requestWithPackageList()
        Async.main(after: 0.1) {
            requestEventSave(title: "进入付费页面", mode: "进入付费页面")
        }
    }
    
    @objc private func rightButtonClicked() {
        self.restorePurchases()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
           super.viewWillDisappear(animated)
       }
    
    //MARK: 付费协议
    @IBAction func paymentAgreementBtnclickAction(_ sender: Any) {
        let web = WebViewController()
        web.modalPresentationStyle = .fullScreen
        web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.paymentAgree) as? String ?? ""
        present(web, animated: true)
    }
    
    //MARK: 订阅协议
    @IBAction func subscriptionProtocolBtnClickAction(_ sender: Any) {
        let web = WebViewController()
        web.modalPresentationStyle = .fullScreen
        web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.autoAgree) as? String ?? ""
        present(web, animated: true)
    }
    
    //MARK: 立即开通按钮点击事件
    @IBAction func openNowBtnClickAction(_ sender: Any) {
        if payIndex >= 0 {
            pay(purchaseProductId: productList[payIndex].prodid.or("")) { _ in
                
            }
        }
    }
    
    
    func pay(purchaseProductId: String, completeHandle: @escaping (Bool) -> Void) {
        if !SwiftyStoreKit.canMakePayments {
            print("您的手机没有打开程序内付费购买")
            completeHandle(false)
            return
        }
        showHUD()
        SwiftyStoreKit.purchaseProduct(purchaseProductId, applicationUsername: "") { [weak self] purchaseResult in
            guard let self = self else { return }
            switch purchaseResult {
            case .success(let purchase):
                //处理交易
                self.handleTransaction(transaction: purchase.transaction)
            case .error(let error):
                Async.main {
                    self.hideHUD()
                }
                //                self.showTips("操作失败，请稍后再试")
                switch error.code {
                case .unknown:
                    print("Unknown error. Please contact support")
                case .clientInvalid:
                    print("Not allowed to make the payment")
                case .paymentCancelled:
                    print("paymentCancelled")
                case .paymentInvalid:
                    print("The purchase identifier was invalid")
                case .paymentNotAllowed:
                    print("The device is not allowed to make the payment")
                case .storeProductNotAvailable:
                    print("The product is not available in the current storefront")
                case .cloudServicePermissionDenied:
                    print("Access to cloud service information is not allowed")
                case .cloudServiceNetworkConnectionFailed:
                    print("Could not connect to the network")
                case .cloudServiceRevoked:
                    print("User has revoked permission to use this cloud service")
                default :
                    print("其他错误")
                }
                
                completeHandle(false)
            }
        }
    }
    
    //2.处理交易
    func handleTransaction(transaction: PaymentTransaction) {
        //获取receipt
        SwiftyStoreKit.fetchReceipt(forceRefresh: false) { [weak self] result in
            guard let self = self else { return }
            switch result {
            case .success(let receiptData):
                let encryptedReceipt = receiptData.base64EncodedString(options: [])
                print("获取校验字符串Fetch receipt success:\n\(encryptedReceipt)")
                //3.服务端校验
                self.requestSubscribeVerify(encryptedReceipt)
                //                if 验证成功 {
                //                    SwiftyStoreKit.finishTransaction(transaction)
                //                }
            case .error( _ ):
                Async.main {
                    self.hideHUD()
                }
                //                self.showTips("操作失败，请稍后再试")
            }
            
        }
    }
    
    func restorePurchases(_ completeHolder: ((Bool)->Void)? = nil) {
        showHUD()
        SwiftyStoreKit.restorePurchases(atomically: false) { [weak self] results in
            guard let self = self else { return }
            if results.restoreFailedPurchases.count > 0 {
                Async.main {
                    self.hideHUD()
                }
                //                self.showTips("操作失败，请稍后再试")
            }else if results.restoredPurchases.count > 0 {
                let purchase: Purchase = results.restoredPurchases.last!
                self.handleTransaction(transaction: purchase.transaction)
            }else {
                self.showTips("暂无可恢复购买的产品")
            }
            if completeHolder != nil {
                completeHolder!(true)
            }
        }
    }
    
    func requestSubscribeVerify(_ subscribe: String) {
        WMAgentApi.shared.requestApi(ApiEnum.subscribeVerify(subscribe)) { res in
            Async.main { [weak self] in
                self?.hideHUD()
                let code: String = res["code"] as! String
                let message: String? = res["message"] as? String
                self?.showTips(message.or(""))
                if code == "200" || code == "0" {
                    self?.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
    
    
    //MARK: 添加套餐
    func addScrollSubView(){
        
        let width = 108.0;
        let originX = 15.0;
        let space = 10.0;
        self.scrollView.contentSize = CGSize(width: 118 * productList.count + 20, height: 150)
        for i in 0..<productList.count {
            let view = UIView.viewFromNib(nibName: "WMMembershipPackageView") as! WMMembershipPackageView
            view.frame = CGRect(x: originX + (width + space) * Double(i), y: 5, width: 108, height: 150)
            view.bacView.tag = 100 + i;
            view.tag = (100 + i) * 100;
            view.listModel = self.productList[i]
            if(i == payIndex){
                view.bacView.layer.borderWidth = 1.0;
                view.bacView.layer.borderColor = UIColor(valueRGB: 0xECC9A8, alpha: 1.0).cgColor
                view.bacView.backgroundColor = UIColor(valueRGB: 0xFAECE5, alpha: 1.0)
                view.limitOpenImageView.isHidden = false
                view.limitOpenLabel.isHidden = false
            }else{
                view.bacView.layer.borderWidth = 1.0;
                view.bacView.layer.borderColor = UIColor.white.cgColor
                view.bacView.backgroundColor = UIColor.white
                view.limitOpenImageView.isHidden = true
                view.limitOpenLabel.isHidden = true
            }
            view.tapGestureClick = { tag in
                self.payIndex = tag - 100
                for i in 0..<self.productList.count {
                    let subView = self.scrollView.viewWithTag((100 + i) * 100) as! WMMembershipPackageView
                    if(self.payIndex != i){
                        subView.bacView.layer.borderWidth = 1.0;
                        subView.bacView.layer.borderColor = UIColor.white.cgColor
                        subView.bacView.backgroundColor = UIColor.white
                    }else{
                        subView.bacView.layer.borderWidth = 1.0;
                        subView.bacView.layer.borderColor = UIColor(valueRGB: 0xECC9A8, alpha: 1.0).cgColor
                        subView.bacView.backgroundColor = UIColor(valueRGB: 0xFAECE5, alpha: 1.0)
                    }
                }
            }
            self.scrollView.addSubview(view)
            
        }
    }
    
    //MARK: 网络请求
    //获取套餐列表
    func requestWithPackageList(){
        WMAgentApi.shared.requestApi(ApiEnum.productList) { res in

            let code: String = res["code"] as? String ?? ""
            guard code == "200" || code == "0" else {
                print("请求失败，错误码: \(code)")
                return
            }
            
            guard let data = res["data"] as? [String: Any],
                  let memberList = data["memberList"] as? [[String: Any]] else {
                print("数据解析失败")
                return
            }
            
            // 清空现有数据
            self.productList.removeAll()
            
            // 将数组转换为模型
            for item in memberList {
                if let model = WMPackageListModel(json: item) {
                    self.productList.append(model)
                }
            }
            
            // 设置默认选中的套餐
            for (index, model) in self.productList.enumerated() {
                if model.defaultshow == 1 {
                    self.payIndex = index
                    break
                }
            }
            
            // 添加滚动视图子视图
            DispatchQueue.main.async {
                self.addScrollSubView()
            }
            
            
        }
    }
}
